package com.edu.servlet;

import com.edu.bean.User;
import com.edu.dao.UserDao;
import com.edu.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/register")
public class UserRegisterServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 如果已经登录，直接跳转到首页
        if (request.getSession().getAttribute("user") != null) {
            response.sendRedirect(request.getContextPath() + "/user/home");
            return;
        }
        request.getRequestDispatcher("/user/register.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String realName = request.getParameter("realName");
        String email = request.getParameter("email");

        // 参数验证
        if (username == null || password == null || confirmPassword == null ||
                username.trim().isEmpty() || password.trim().isEmpty() || confirmPassword.trim().isEmpty()) {
            request.setAttribute("error", "用户名和密码不能为空");
            request.getRequestDispatcher("/user/register.jsp").forward(request, response);
            return;
        }

        // 验证两次密码是否一致
        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的密码不一致");
            request.getRequestDispatcher("/user/register.jsp").forward(request, response);
            return;
        }

        // 检查用户名是否已存在
        if (userDao.checkUsernameExists(username, null)) {
            request.setAttribute("error", "用户名已存在");
            request.getRequestDispatcher("/user/register.jsp").forward(request, response);
            return;
        }

        // 创建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(MD5Util.md5(password));
        user.setRoleId(2); // 设置为普通用户
        user.setRealName(realName);
        user.setEmail(email);

        // 保存用户
        if (userDao.add(user)) {
            // 注册成功，跳转到登录页
            response.sendRedirect(request.getContextPath() + "/user/login.jsp");
        } else {
            request.setAttribute("error", "注册失败，请稍后重试");
            request.getRequestDispatcher("/user/register.jsp").forward(request, response);
        }
    }
}